package com.jwt.Filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

@SuppressWarnings("unchecked")
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
	private Logger logger= LoggerFactory.getLogger(getClass());
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		String token = request.getHeader("Authorization");
		if (token != null) {
			Claims claims= Jwts.parser()
					.setSigningKey("jwtccsss")
					.parseClaimsJws(token)
					.getBody();
			Date claimsExpiration = claims.getExpiration();
			Date now = new Date();
			if (now.getTime()>claimsExpiration.getTime()) {
				throw  new AuthenticationServiceException("凭证已过期，请重新登录");
			}
			LinkedHashMap<String, Object> authenticationMap = (LinkedHashMap<String, Object>) claims.get("authentication");
			String name = (String) authenticationMap.get("name");
			ArrayList<LinkedHashMap<String, String>> authenticationList = (ArrayList<LinkedHashMap<String, String>>) authenticationMap.get("authorities");
			String[] authenticationStr = new String[authenticationList.size()];
			for (int i = 0; i < authenticationStr.length; i++) {
				authenticationStr[i]=authenticationList.get(i).get("authority");
			}
			List<GrantedAuthority>authorities = AuthorityUtils.createAuthorityList(authenticationStr);
			UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(name, null, authorities);
			SecurityContextHolder.getContext().setAuthentication(authentication);
		}
		filterChain.doFilter(request, response);
	}
}
